using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using StockTraderRI.Modules.News.Contract;
using StockTraderRI.Modules.News.Properties;

namespace StockTraderRI.Modules.News.Server
{
    public class NewsRepository : INewsRepository
    {
        private readonly Queue<NewsDto> news = new Queue<NewsDto>();

        public NewsRepository()
        {
            news = LoadNews();
        }

        public NewsDto FindNewsToPublish()
        {
            if (news.Count == 0)
            {
                return null;
            }

            return news.Dequeue();
        }

        private static Queue<NewsDto> LoadNews()
        {
            var document = XDocument.Parse(Resources.News);
            var newsData = document.Descendants("NewsItem")
                .Select(x => new NewsDto
                                 {
                                     TickerSymbol = x.Attribute("TickerSymbol").Value,
                                     Title = x.Element("Title").Value,
                                     Body = x.Element("Body").Value
                                 })
                .OrderBy(news => news.Title);

            return new Queue<NewsDto>(newsData);
        }
    }
}